import { BaseController } from '../BaseController';
import {Md5} from 'ts-md5/dist/md5';
import { json } from 'body-parser';
import {ConnPoolInstance} from '../../AppDatabase';
import {PaymentLogger} from '../../Logger';


export class bilibili extends BaseController {
    protected SECRET_KEY: string = "d247df029507433685be5235ee6d4e45";

    async Start(){
        try{
            let data: string = this.request.body.data;
            let jsonData = JSON.parse(data);
    
            let verfiySign: Number = this.sign(jsonData, this.SECRET_KEY);
    
            await this.saveToDb(jsonData, verfiySign);
        }catch(e){
            PaymentLogger.error("bilibili error: " + <string>e + " body: " + JSON.stringify(this.request.body));
        }finally{
            this.response.send("success");
        }
    }

    sign(jsonData: any, secretKey: string): Number{
        let sign = jsonData["sign"];

        let keys = Object.keys(jsonData);
        let sortKeys = keys.sort();

        let toSignStr: string;
        toSignStr = jsonData["game_money"] + jsonData["money"] + jsonData
        sortKeys.forEach(key => {
            if (key.toLocaleLowerCase() != "item_name" && 
                key.toLocaleLowerCase() != "item_desc" &&
                key.toLocaleLowerCase() != "token" &&
                key.toLocaleLowerCase() != "sign")
            {
                    toSignStr += jsonData[key];
            }
        });
        let data = toSignStr + secretKey;
        let strMd5 = <string>Md5.hashStr(data);

        if (strMd5 == jsonData["sign"]){
            return 1;
        }

        return 0;
    }

    async saveToDb(jsonData: any, verfiySign: Number){
        let sql = "INSERT INTO bilibili_payment_log SET ?";
        let data = {
            orderId: jsonData["id"],
            order_no: jsonData["order_no"],
            out_trade_no: jsonData["out_trade_no"],
            uid: jsonData["uid"],
            username: jsonData["username"],
            role: jsonData["role"],
            money: jsonData["money"], 
            pay_money: jsonData["pay_money"],
            game_money: jsonData["game_money"],
            merchant_id: jsonData["merchant_id"],
            game_id: jsonData["game_id"],
            zone_id: jsonData["zone_id"],
            product_name: jsonData["product_name"],
            product_desc: jsonData["product_desc"],
            pay_time: jsonData["pay_time"],
            client_ip: jsonData["client_ip"],
            extension_info: jsonData["extension_info"],
            order_status: jsonData["order_status"],
            sign: jsonData["sign"],
            verifySign: verfiySign
        };
        
        let ret = await ConnPoolInstance.Insert(sql, data);

        return ret;
    }
}
